﻿using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using QuartzServices.Domain.Interfaces;

namespace QuartzServices.Domain.Common.HttpServices
{
    public class BlcSapLocationClient
    {
        private readonly HttpClient _httpClient;
        private readonly IConfiguration _configuration;
        private readonly IJabilApiTokenRepository _jabilApiTokenRepository;

        public BlcSapLocationClient(
            HttpClient httpClient,
            IConfiguration configuration,
            IJabilApiTokenRepository jabilApiTokenRepository)
        {
            _httpClient = httpClient;
            _configuration = configuration;
            _jabilApiTokenRepository = jabilApiTokenRepository;
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public async Task<JObject> GetDataAsync(string jsonData) 
        {
            var token = await GetTokenAsync();

            _httpClient.DefaultRequestHeaders.Authorization =
                new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

            var url = _configuration.GetSection("BlcSapLocation").Value;

            var content = new StringContent(jsonData);

            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

            var responseBody = string.Empty;
            try
            {
                var response = await _httpClient.PostAsync(url, content);
                response.EnsureSuccessStatusCode();
                responseBody = await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                throw new Exception($"请求接口时异常：{ex}");
            }

            var obj = JObject.Parse(responseBody);

            if (obj.GetValue("code").ToString() != "200") 
            {
                throw new Exception($"返回值异常：{responseBody}");
            }

            return obj;
        }

        /// <summary>
        /// 获取token
        /// </summary>
        /// <returns></returns>
        private async Task<string> GetTokenAsync() 
        {
            var jabilApiToken = await _jabilApiTokenRepository.GetLatest();

            return jabilApiToken == null ? throw new Exception("没有获取到token") : jabilApiToken.Token;
        }
    }
}
